/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.gateway.context;





import org.asiainfo.ability.gateway.vo.Token;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: visen
 * @Date: 2018/1/29
 * @Description:
 */
public class AbilityApplicationContext {
    private final static ConcurrentHashMap<String, Token> TOKENS = new ConcurrentHashMap(128);
    public final static void putToken(String clientId, Token token) {
        Token oldToken = TOKENS.putIfAbsent(clientId, token);
        if(oldToken != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE,10);
            oldToken.setExpireTime(calendar.getTime());
            token.setOldToken(oldToken);
        }
    }
    public final static  boolean checkToken(String clientId, String tokenValue) {
        Token token = TOKENS.get(clientId);
        if(token == null) {
            return false;
        }
        if(token.getExpireTime().before(new Date())) {
            TOKENS.remove(clientId);
        } else if(tokenValue.equals(token.getValue())) {
            return true;
        }
        if(token.getOldToken() != null) {
            if(token.getOldToken().getExpireTime().before(new Date())) {
                token.setOldToken(null);
            } else if(tokenValue.equals(token.getOldToken().getValue())) {
                return true;
            }
        }
        return false;
    }

}
